package masterjava.common.client.gxt.base.tree;

import com.extjs.gxt.ui.client.data.ModelIconProvider;
import com.extjs.gxt.ui.client.data.TreeLoader;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import masterjava.common.client.gxt.base.model.GenericListener;
import masterjava.common.client.gxt.base.model.GenericModel;

/**
 * User: gkislin
 * Date: 8/1/11
 */
public class GenericTreePanel extends TreePanel<GenericTreeModel> {

    public GenericTreePanel(TreeLoader<GenericTreeModel> treeLoader) {
        super(new GenericTreeStore(treeLoader));
        setDisplayProperty(GenericModel.KEY);
        setIconProvider(new ModelIconProvider<GenericTreeModel>() {

            public AbstractImagePrototype getIcon(GenericTreeModel model) {
                return (model.getType() == null) ? null : IconHelper.createStyle(model.getType().getCssStyle());
            }
        });
    }

    public StoreFilterField<GenericTreeModel> bindFilter() {
        StoreFilterField<GenericTreeModel> filter = new StoreFilterField<GenericTreeModel>() {
            @Override
            protected boolean doSelect(Store<GenericTreeModel> store,
                                       GenericTreeModel parent, GenericTreeModel record, String property,
                                       String filter) {
                // only match leaf nodes
                if (record instanceof FolderModel) {
                    return false;
                }
                String name = record.getKey().toLowerCase();
                if (name.startsWith(filter.toLowerCase())) {
                    return true;
                }
                return false;
            }
        };
        filter.bind(store);
        return filter;
    }

    public void addListener(EventType type, final GenericListener<GenericTreeModel> listener) {
        super.addListener(type, new Listener<TreePanelEvent<GenericTreeModel>>() {
            @Override
            public void handleEvent(TreePanelEvent<GenericTreeModel> be) {
                listener.onEvent(be.getItem());
            }
        });
    }
}
